package service

import (
	"ruanGongKeShe16Zu/common/utils"
	"ruanGongKeShe16Zu/model"
	"ruanGongKeShe16Zu/repository"
	"ruanGongKeShe16Zu/service/vo"
	"sync"

	"github.com/gin-gonic/gin"
)

// 单例实现
var CategoryServiceInstance *CategoryService
var CategoryServiceOnce sync.Once

type CategoryService struct {
	Repository repository.CategoryRepository
}

func GetCategoryService() *CategoryService {
	CategoryServiceOnce.Do(func() {
		repository := repository.NewCategoryRepository().(repository.CategoryRepository)
		repository.DB.AutoMigrate(&model.Category{})
		CategoryServiceInstance = &CategoryService{
			Repository: repository,
		}
	})
	return CategoryServiceInstance
}

func (s *CategoryService) Create(ctx *gin.Context, req *vo.CategoryReq) (*model.Category, error) {
	category, err := s.Repository.Create(req.Name)
	if err != nil {
		// utils.LogrusObj.Error(err)
		return nil, err
	}
	return category, nil
}

func (s *CategoryService) Retrieve(ctx *gin.Context, id int) (*model.Category, error) {
	category, err := s.Repository.SelectById(id)
	if err != nil {
		// utils.LogrusObj.Error(err)
		return nil, err
	}
	return category, nil
}

func (s *CategoryService) Update(ctx *gin.Context, item *model.Category, name string) (*model.Category, error) {
	category, err := s.Repository.Update(*item, name)
	if err != nil {
		utils.LogrusObj.Error(err)
		return nil, err
	}
	return category, nil
}

func (s *CategoryService) Delete(ctx *gin.Context, id int) error {
	err := s.Repository.DeleteById(id)
	if err != nil {
		utils.LogrusObj.Error(err)
		return err
	}
	return nil
}

// CategoryList 列举分类
func (s *CategoryService) CategoryList(ctx *gin.Context, req *vo.ListCategoryReq) (resp *vo.DataListResp, err error) {
	categories, err := s.Repository.CategoryList()
	if err != nil {
		// utils.LogrusObj.Error(err)
		return
	}
	cResp := make([]*vo.ListCategoryResp, 0)
	for _, v := range categories {
		cResp = append(cResp, &vo.ListCategoryResp{
			ID:           v.ID,
			CategoryName: v.Name,
			CreatedAt:    v.CreatedAt.Unix(),
		})
	}

	resp = &vo.DataListResp{
		Item:  cResp,
		Total: int64(len(cResp)),
	}

	return
}
